package threadUtils.demo04;


import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore对资源进行限流
 */
public class SemaphoreExample01 {

    final static int MAX_PLAYER = 10;

    public static void main(String[] args) {

        LoginService loginService = new LoginService(MAX_PLAYER);

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                if (loginService.login(Thread.currentThread().getName())) {
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    loginService.logout(Thread.currentThread().getName());
                }
            }).start();
        }

    }

}

class LoginService {

    Semaphore semaphore;

    public LoginService(int max) {
        this.semaphore = new Semaphore(max, true);
    }

    public boolean login(String name) {

        if (semaphore.tryAcquire()) { // 非阻塞，第一次进不来，就永远进不来
            System.out.println(name + " login success");
            return true;
        }
        System.out.println(name + " login failed");
        return false;
    }

    public void maxLogin(String name) throws InterruptedException {
        semaphore.acquire(); // 阻塞，永远都可以进来
        System.out.println(name + " login success");
    }

    public void logout(String name) {
        semaphore.release();
        System.out.println(name + " login failed");
    }
}